package com.cn.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chenyuncong on 2019/4/30.
 */
public class FileUtils {
    public static void readFile() {
        String pathname = "D:\\testData\\tables.txt"; // 绝对路径或相对路径都可以，写入文件时演示相对路径,读取以上路径的input.txt文件
        //防止文件建立或读取失败，用catch捕捉错误并打印，也可以throw;
        //不关闭文件会导致资源的泄露，读写文件都同理
        //Java7的try-with-resources可以优雅关闭文件，异常时自动关闭文件；详细解读https://stackoverflow.com/a/12665271
        StringBuffer sb = new StringBuffer();

        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader) // 建立一个对象，它把文件内容转成计算机能读懂的语言
        ) {
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                System.out.println(line.substring(14, 53));
                sb.append("\"").append(line.substring(14, 53).trim()).append("\" ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
    }

    public static String txt2String(String path) {
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        if(file.exists()){
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
                String s = null;
                while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                    result.append(s);
//                    System.out.println(s);
                }
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result.toString();
    }

    public static void fileToData(String path, String outPath) throws IOException {
        File file = new File(path);
//        StringBuilder result = new StringBuilder();
        BufferedReader br = null;
        Set<String> set=new HashSet<>();
//        BufferedWriter out =null;
        try {
            if (file != null) {
                File writeName = new File(outPath); // 相对路径，如果没有则要建立一个新的output.txt文件
                writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
                try (
                        FileWriter writer = new FileWriter(writeName);
                        BufferedWriter out = new BufferedWriter(writer)
                ) {

                    br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
                    String s = null;
                    JSONObject obj = null;
                    String[] phones = null;
                    while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                        obj = JSON.parseObject(s);
//                        System.out.println(s);
                        s = obj.get("customerPhone").toString().replaceAll(" ", "");
                        phones = s.split(",");
                        if (phones.length == 1) {
                            s = phones[0];
                        } else if (phones.length > 1) {
                            if (StringUtils.isEmpty(phones[0])) {
                                s = phones[1];
                            } else {
                                s = phones[0];
                            }
                        }
                        if(isPhone(s)){
//                            out.write(s + "\r\n");
                            set.add(s);
                        }

                    }

                    for(String x:set){
                        out.write(getMD5(x) + "\r\n");
                    }
                    out.close();
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                br.close();
            }
        }

    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) throws IOException {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            throw new IOException("MD5加密出现错误");
        }
    }
    public static boolean isPhone(String phone) {
        String regex = "^[1][3456789][0-9]{9}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    public static void main(String[] args) throws IOException {
//        readFile();
//        fileToData("D:\\testData\\fd_output.txt", "D:\\testData\\fd_result.txt");
//        System.out.println(isPhone("11355356626"));
//        System.out.println(getMD5("fgsdf"));

//        txt2String("D:\\testData\\fd_output2.txt");
        long startTime=System.currentTimeMillis();
        txt2String("F:\\file2\\alg-customer-finally.json");
        System.out.println(System.currentTimeMillis()-startTime);
    }
}
